<template>
    <div id="shop-fromPop" @click="handleToClosePop">
        <div class="shop-fromPop-content" @click.stop="">
            <div class="shop-fromPop-content-header">
                <h2>{{title}}</h2>
                <p><i class="el-icon-close" @click="handleToClosePop"></i></p>
            </div>

            <div class="shop-fromPop-content-from" >
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                    <el-form-item label="分类" prop="cate_id">
                        <el-select v-model="ruleForm.cate_id" placeholder="请选择分类" clearable>
                            <el-option :label="data.name" :value="data.id" v-for="data in Classification" :key="data.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="名称" prop="name">
                        <el-input
                            type="text"
                            v-model="ruleForm.name"
                            maxlength="50"
                            show-word-limit
                        >
                        </el-input>
                    </el-form-item>

                    <el-form-item label="宣传语" prop="slogan">
                        <el-input
                            type="text"
                            v-model="ruleForm.slogan"
                            maxlength="200"
                            show-word-limit
                        >
                        </el-input>
                    </el-form-item>

                   <el-form-item label="公告" prop="notice">
                        <el-input
                            type="text"
                            v-model="ruleForm.notice"
                            maxlength="200"
                            show-word-limit
                        >
                        </el-input>
                    </el-form-item>

                    <el-form-item label="手机号" prop="mobile">
                        <el-input
                            type="text"
                            v-model="ruleForm.mobile"
                            maxlength="11"
                            show-word-limit
                        >
                        </el-input>
                    </el-form-item>

                    <el-form-item label="地址" prop="address">
                        <el-input
                            type="text"
                            v-model="ruleForm.address"
                            maxlength="200"
                            show-word-limit
                             placeholder="详细地址"
                        >
                        </el-input>
                        <div class="map-autocomplete-box">
                            <el-autocomplete
                            style="width:100%;"
                            popper-class="autoAddressClass"
                            v-model="ruleForm.address"
                            :fetch-suggestions="querySearchAsync"
                            :trigger-on-focus="false"
                            @select="handleSelect"
                            clearable>
                                <template slot-scope="{ item }">
                                    <div class="el-ul-searchData" style="display:flex;">
                                        <i class="el-icon-search fl mgr10" style="line-height:34px;padding-right:10px"></i>
                                        <div style="overflow:hidden;display:flex;">
                                            <div class="title">{{ item.title }}</div>
                                            <span class="address ellipsis" style="color:#9095a6;padding-left:5px">{{ ' ' + item.address }}</span>
                                        </div>
                                    </div>
                                </template>
                                <el-button icon="el-icon-search" slot="append" @click="okMap"></el-button>
                            </el-autocomplete>
                        </div>
                        <div id="allmap">
                        </div>
                    </el-form-item>

                    <el-form-item label="店铺头像" prop="avatar">
                        <div class="shop-fromPop-content-from-avatar">
                            <el-upload
                                class="upload-demo"
                                drag
                                action="/backend/api/imageUpload?"
                                :headers="headers"
                                :on-success="handleAvatarSuccessAvatar"
                                multiple
                                :show-file-list="false">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">推荐尺寸比例（宽 * 高）：138 * 138</div>
                            </el-upload>
                            <div class="nowFileIcon">
                                <img v-if="ruleForm.avatar" :src="ruleForm.avatar" alt="图片加载失败">
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="店铺主图" prop="image">
                        <div class="shop-fromPop-content-from-avatar">
                            <el-upload
                                class="upload-demo"
                                drag
                                action="/backend/api/imageUpload?"
                                :headers="headers"
                                :on-success="handleAvatarSuccessImage"
                                multiple
                                :show-file-list="false">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">推荐尺寸比例（宽 * 高）：320 * 140</div>
                            </el-upload>
                            <div class="nowFileIcon">
                                <img v-if="ruleForm.image" :src="ruleForm.image" alt="图片加载失败">
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="营业时间" prop="open_time">
                        <el-select v-model="ruleForm.open_time" placeholder="请选择营业时间" clearable>
                            <el-option :label="data.name" :value="data.id" v-for="data in openTimeList" :key="data.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="人均单价" prop="personal_price">
                        <el-select v-model="ruleForm.personal_price" placeholder="请选择人均单价" clearable>
                            <el-option :label="data.name" :value="data.id" v-for="data in personalPrice" :key="data.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="介绍" prop="description">
                        <div class="components-container">
                            <div>
                                <tinymce v-model="ruleForm.description" :height="300" />
                            </div>
                            
                        </div>
                    </el-form-item>

                     <el-form-item label="优惠活动" prop="activity">
                        <el-select v-model="ruleForm.activity" multiple placeholder="请选择">
                            <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    
                    <el-form-item label="置顶" prop="top">
                        <el-switch v-model="top"></el-switch>
                    </el-form-item>

                    <el-form-item label="状态" prop="status">
                        <el-switch v-model="status"></el-switch>
                    </el-form-item>
                    
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                        <el-button @click="handleToClosePop">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'

export default {
    name: 'formPop',
    props: {
        title: {
            type: String,
            default: '添加店铺'
        },
        Classification: {
            type: Array,
            default: []
        },
        fromData: {
            type: Object,
            default: {}
        }
    },
    components: { 
        Tinymce 
    },
    data() {
        return {
            map: {},
            mk: {},
            top: false,
            status: true,
            ruleForm: {
                cate_id: '',
                name: '',
                slogan: '',
                notice: '',
                mobile: '',
                address: '',
                lng: 114.31158595642933,
                lat: 30.598466503263325,
                avatar:'',
                image: '',
                delivery: false,
                description: '',
                activity: [],
                open_time: null,
                personal_price: null,
                top: 0,
                status: 1
            },
            headers: {
                Authorization: 'Bearer ' + window.localStorage.getItem('token')
            },
            rules: {
                cate_id: [
                    { required: true, message: '请选择分类', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ],
                slogan: [
                    { required: true, message: '请输入宣传语', trigger: 'blur' },
                ],
                notice: [
                    { required: true, message: '请输入公告', trigger: 'blur' },
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' },
                ],
                avatar: [
                    { required: true, message: '请上传店铺头像', trigger: 'change' },
                ],
                image: [
                    { required: true, message: '请上传店铺主图', trigger: 'change' },
                ],
                open_time: [
                    { required: true, message: '请选择营业时间', trigger: 'change' }
                ],
                personal_price: [
                    { required: true, message: '请选择人均单价', trigger: 'change' }
                ]
            },
            options: [{
                value: 1,
                label: '全场8.5折'
            }, {
                value: 2,
                label: '充200送50'
            }, {
                value: 3,
                label: '新店开业'
            }, {
                value: 4,
                label: '会员5折'
            }, {
                value: 5,
                label: '冲500万送女朋友'
            }],
            openTimeList: [
                {
                    name: '24小时营业',
                    id: 1
                },
                {
                    name: '白天营业',
                    id: 2
                },
                {
                    name: '夜间营业',
                    id: 3
                },
            ],
            personalPrice: [               
                {
                    name: '10以上',
                    id: 10
                },
                {
                    name: '20以上',
                    id: 20
                },
                {
                    name: '30以上',
                    id: 30
                },
                {
                    name: '40以上',
                    id: 40
                },
                {
                    name: '70以上',
                    id: 70
                },
                {
                    name: '100以上',
                    id: 100
                },
                {
                    name: '200以上',
                    id: 200
                },
                {
                    name: '300以上',
                    id: 300
                },
                {
                    name: '400以上',
                    id: 400
                },
                {
                    name: '500以上',
                    id: 500
                },
            ],
        };
    },
    methods: {
        //退出
        handleToClosePop(){
            this.$emit("closePop")
        },
        //确认
        submitForm(formName) {
            let data = {};
            let interfaceUrl = '/backend/api/merchant';
            //判断传参
            if(this.fromData.name){
                interfaceUrl = interfaceUrl + `/${this.fromData.id}`
                // for(let i in this.ruleForm){
                //     this.fromData[i] = this.ruleForm[i];
                // }
                //Object.assign(data, this.ruleForm);
                var method = 'put';
                console.log(data)
            }else{
                //Object.assign(data, this.ruleForm)
                var method = 'post'
            }


            //上传
            this.$refs[formName].validate((valid) => {
            if (valid) {
                console.log(this.ruleForm)
                this.$http({
                    method: method,
                    url: interfaceUrl,
                    data: this.ruleForm
                }).then(res => {
                    console.log('成功')
                    this.$emit('addPopToFile')
                    this.handleToClosePop()
                }).catch(err=>{
                    this.$message.error('上传失败，请重试');
                })
            } else {
                return false;
            }
            });
        },
        // 上传头像
        handleAvatarSuccessAvatar(response, file, fileList){
            this.ruleForm.avatar = file.response.url
        },
        // 上传主图
        handleAvatarSuccessImage(response, file, fileList){
            this.ruleForm.image = file.response.url
        },
        //主模块（地图）
        loadMainJScript() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://api.map.baidu.com/getscript?v=3.0&ak=Nw8Rz1ZqOfsUdYVK2TLuQN4fANGWvYWl';
            script.onload = () => {
                this.init();
            }
            document.body.appendChild(script);
        },
        //创建Map实例
        init() {
            var that = this;
            this.map = new BMap.Map("allmap", {enableMapClick:false})  //新建地图实例，enableMapClick:false ：禁用地图默认点击弹框
            var point = new BMap.Point(this.ruleForm.lng,this.ruleForm.lat);
            this.map.centerAndZoom(point,16)// 创建点坐标
            this.map.setCurrentCity("北京")

            // this.map.enableScrollWheelZoom(true);  // 启用滚轮放大缩小

            this.mk = new BMap.Marker(point,{enableDragging:false}) //创建一个图像标注实例，enableDragging：是否启用拖拽，默认为false
            this.map.addOverlay(this.mk) //将覆盖物添加到地图中
            this.map.addEventListener('click', function(e){ 
                that.getAddrByPoint(e.point) //点击后调用逆地址解析函数，e.point为拖拽后的地理坐标
            })

            var navigationControl = new BMap.NavigationControl({ //创建一个特定样式的地图平移缩放控件
                anchor: BMAP_ANCHOR_TOP_RIGHT, //靠右上角位置
                type: BMAP_NAVIGATION_CONTROL_SMALL //SMALL控件类型
            })
            this.map.addControl(navigationControl ) //将控件添加到地图
            
            
        },
        //逆地址解析函数（根据坐标点获取详细地址）
        getAddrByPoint(point){
            var that = this;
            var geco = new BMap.Geocoder();
            geco.getLocation(point, function(res){
                that.mk.setPosition(point) //重新设置标注的地理坐标
                that.map.panTo(point)  //将地图的中心点更改为给定的点
                that.ruleForm.address = res.address;  //记录该点的详细地址信息
                that.ruleForm.lng = point.lng;  //记录当前坐标点
                that.ruleForm.lat = point.lat;  //记录当前坐标点
            })
        },
        //搜索方法
        querySearchAsync(str,cb){
            var options = {
                onSearchComplete: function(res){ //检索完成后的回调函数
                    console.log(res)
                    var s = [];
                    if (local.getStatus() == BMAP_STATUS_SUCCESS){
                        for (var i = 0; i < res.getCurrentNumPois(); i ++){
                            s.push(res.getPoi(i));
                        }
                        cb(s) //获取到数据时，通过回调函数cb返回到<el-autocomplete>组件中进行显示
                    } else{
                        cb(s)
                    }
                }
            }
            var local = new BMap.LocalSearch(this.map, options) //创建LocalSearch构造函数
            local.search(str) //调用search方法，根据检索词str发起检索
        },
        //选中时的触发方法
        handleSelect(item) {
            this.ruleForm.address = item.address + item.title; //记录详细地址，含建筑物名
            this.ruleForm.lng = item.point.lng; //记录当前选中地址坐标
            this.ruleForm.lat = item.point.lat; //记录当前选中地址坐标
            this.map.clearOverlays() //清除地图上所有覆盖物
            this.mk = new BMap.Marker(item.point) //根据所选坐标重新创建Marker
            this.map.addOverlay(this.mk) //将覆盖物重新添加到地图中
            this.map.panTo(item.point) //将地图的中心点更改为选定坐标点
        },
        okMap(){
            var local = new BMap.LocalSearch(this.ruleForm.address, {
                renderOptions: {
                    map: this.map,
                    autoViewport: true},
                pageCapacity: 8});      
            local.search(this.ruleForm.address);
        }
    },
    mounted(){
        this.loadMainJScript();
        // 编辑店铺，判断状态
        if(this.fromData.name){
            for(let i in this.ruleForm){
                this.ruleForm[i] = this.fromData[i]
            }
            if(this.ruleForm.status == 2){
                this.status = false
            }else{
                this.status = true
            }
            if(this.ruleForm.top == 0){
                this.top = false
            }else{
                this.top = true
            }
        }
    },
    watch: {
        top(){
            this.ruleForm.top = this.top ? 1 : 0;
        },
        status(){
            this.ruleForm.status = this.status ? 1 : 2;
        }
    }
}
</script>

<style lang="scss" scoped>
#shop-fromPop{
    width: 100%;
    height: 100%;
    background: rgba(24, 24, 24, 0.5);;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 10;
    .shop-fromPop-content{
        width: 50%;
        height: 60%;
        background: white;
        position: absolute;
        top: 20%;
        left: 25%;
        overflow: auto;
    }

    .shop-fromPop-content-header{
        display: flex;
        justify-content: space-between;
        height: 60px;
        padding: 0 20px;
        margin-bottom: 20px;
        h2{
            font-size: 18px;
            line-height: 60px;
        }
        p{
            font-size: 13px;
            line-height: 60px;
            color: #9095a6;
        }
    }
    
    .shop-fromPop-content-from{
        padding-right: 20px;
    }

    .nowFileIcon{
        flex: 1;
        max-width: 360px;
        height: 178px;
        border: 1px dashed #d9d9d9;
        border-radius: 8px;
        margin-left: 25px;
        overflow: hidden;
        img{
            width: 100%;
            height: auto;
            transform: translateY(calc(-50% + 89px));
        }
    }
    
    .shop-fromPop-content-from-avatar{
        display: flex;
    }

    /deep/ .el-upload-dragger{
        max-width: 360px;
        flex: 1;
    }

    #allmap{
        height: 300px;
        margin-top: 20px;
    }

    .map-autocomplete-box{
        max-width: 300px;
        position: absolute;
        left: 10px;
        top: 70px;
        z-index: 10;
    }

    .editor-content{
        margin-top: 20px;
    }
}
</style>